package hcb.dms.khachHang;

import hcb.dms.GPSTracker;
import hcb.dms.JSONParser;
import hcb.dms.R;
import hcb.dms.UserSessionManager;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class Edit_khachHang extends Activity {


	EditText txMaKH, txTenKH, txDiaChi, txDienThoai,txGhiChu,txMST;
	Button btnSave, btnDelete, btUpdateGPS;

	String pid;
	JSONObject objX;

	// Progress Dialog
	private ProgressDialog pDialog;

	// JSON parser class
	JSONParser jsonParser = new JSONParser();
	JSONObject product;

	// JSON Node names
	// JSON Node names
	private static final String TAG_SUCCESS = "success";
	private static final String TAG_KHACHHANG = "khachHang";
	private static final String TAG_MESSAGE = "message";
	private static final String TAG_MAKH = "maKH";
	private static final String TAG_TENKH = "tenKH";
	private static final String TAG_DIACHI = "diaChi";
	private static final String TAG_LIENHE = "lienHe";
	private static final String TAG_DIENTHOAI = "dienThoai";
	private static final String TAG_GPSLAT = "gpsLat";
	private static final String TAG_GPSLONG = "gpsLong";

	private static final String TAG_GHICHU = "ghiChu";
	private static final String TAG_MST = "maSoThue";

	// products JSONArray
	JSONArray products = null;
	UserSessionManager session;


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.edit_khach_hang);
		session = new UserSessionManager(getApplicationContext());
		// save button
		btnSave = (Button) findViewById(R.id.btSave);
		btnDelete = (Button) findViewById(R.id.btDelete);
		btUpdateGPS = (Button) findViewById(R.id.btUpdateGPS);

		// getting product details from intent
		Intent i = getIntent();

		// getting product id (pid) from intent
		pid = i.getStringExtra(TAG_MAKH);
		// Getting complete product details in background thread
		new GetKhachHangDetails().execute();

		// save button click event
		btnSave.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// starting background task to update product
				new SaveKhachHangDetails().execute();
			}
		});

		// Delete button click event
		btnDelete.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// deleting khach hang in background thread
				new DeleteKhachHang().execute();
			}
		});
		btUpdateGPS.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// update gps  in background thread
				new UpdateGPSKhachHangDetails().execute();
			}
		});

	}


	class GetKhachHangDetails extends AsyncTask<String, String, JSONObject> {

		/**
		 * Before starting background thread Show Progress Dialog
		 */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(Edit_khachHang.this);
			pDialog.setMessage("Loading khach hang. Please wait...");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(true);
			pDialog.show();
		}

		/**
		 * Getting product details in background thread
		 */
		protected JSONObject doInBackground(String... params) {
			int success;
			try {
				//Building Parameters
				// Building Parameters
				List<NameValuePair> paramas = new ArrayList<NameValuePair>();
				paramas.add(new BasicNameValuePair(session.KEY_USERNAME, session.getUsername()));
				paramas.add(new BasicNameValuePair(session.KEY_PASSWORD, session.getPassword()));
				paramas.add(new BasicNameValuePair(session.TAG_DANGNHAP, "OK"));
				paramas.add(new BasicNameValuePair(session.TAG_THAOTAC, "LKHBID"));
				paramas.add(new BasicNameValuePair(session.TAG_PID,pid));
				//getting product details by making HTTP request
				//Note that product details url will use GET request
				JSONObject json = jsonParser.makeHttpRequest(session.URL, "POST", paramas);

				success = json.getInt(TAG_SUCCESS);
				if (success == 1) {
					//successfully received product details
					JSONArray productObj = json.getJSONArray(TAG_KHACHHANG); //JSON Array

					//get first product object from JSON Array
					product = productObj.getJSONObject(0);
					return product;

				} else {
					//product with pid not found
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
			return null;
		}
		/**
		 * After completing background task Dismiss the progress dialog
		 * *
		 */
		//After completing background task dismiss the progress dialog
		protected void onPostExecute(JSONObject obj) {
			//Edit text
			txMaKH = (EditText) findViewById(R.id.txMaKH);
			txTenKH = (EditText) findViewById(R.id.txTenKH);
			txDiaChi = (EditText) findViewById(R.id.txDiaChi);
			txDienThoai = (EditText) findViewById(R.id.txDienThoai);
			txGhiChu = (EditText)findViewById(R.id.txGhiChu);
			txMST = (EditText)findViewById(R.id.txMST);

			objX = obj;
			//display product data in editText
			try {
				txMaKH.setText(obj.getString(TAG_MAKH));
				txTenKH.setText(obj.getString(TAG_TENKH));
				txDiaChi.setText(obj.getString(TAG_DIACHI));
				txDienThoai.setText(obj.getString(TAG_DIENTHOAI));
				txGhiChu.setText(obj.getString(TAG_GHICHU));
				txMST.setText(obj.getString(TAG_MST));
			} catch (JSONException e) {
				e.printStackTrace();
			}
			//dismiss the dialog once got all details
			pDialog.dismiss();
		}
	}

	/**
	 * Background Async Task to  Save product Details
	 */
	class SaveKhachHangDetails extends AsyncTask<String, String, String> {
		/**
		 * Before starting background thread Show Progress Dialog
		 */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(Edit_khachHang.this);
			pDialog.setMessage("Saving khach hang ...");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(true);
			pDialog.show();
		}

		/**
		 * Saving product
		 */
		protected String doInBackground(String... args) {

			// getting updated data from EditTexts
			txMaKH = (EditText) findViewById(R.id.txMaKH);
			txTenKH = (EditText) findViewById(R.id.txTenKH);
			txDiaChi = (EditText) findViewById(R.id.txDiaChi);
			txDienThoai = (EditText) findViewById(R.id.txDienThoai);
			txGhiChu = (EditText) findViewById(R.id.txGhiChu);
			txMST = (EditText) findViewById(R.id.txMST);

			String maKH = txMaKH.getText().toString();
			String tenKH = txTenKH.getText().toString();
			String diaChi = txDiaChi.getText().toString();
			String dienThoai = txDienThoai.getText().toString();
			String ghiChu = txGhiChu.getText().toString();
			String mast = txMST.getText().toString();

			try {
				objX.put(TAG_MAKH, maKH);
				objX.put(TAG_TENKH,tenKH);
				objX.put(TAG_DIACHI,diaChi);
				objX.put(TAG_DIENTHOAI,dienThoai);
				objX.put(TAG_GHICHU,ghiChu);
				objX.put(TAG_MST,mast);
			} catch (JSONException e) {
				e.printStackTrace();
			}


			// Building Parameters
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair(session.KEY_USERNAME, session.getUsername()));
			params.add(new BasicNameValuePair(session.KEY_PASSWORD, session.getPassword()));
			params.add(new BasicNameValuePair(session.TAG_DANGNHAP, "OK"));
			params.add(new BasicNameValuePair(session.TAG_THAOTAC, "UKH"));
			params.add(new BasicNameValuePair(session.TAG_PID,pid));
			params.add(new BasicNameValuePair(session.TAG_OBJ, objX.toString()));


			// sending modified data through http request
			// Notice that update product url accepts POST method
			JSONObject json = jsonParser.makeHttpRequest(session.URL,"POST", params);

			// check json success tag
			try {
				int success = json.getInt(TAG_SUCCESS);

				if (success == 1) {
					// send result code 100 to notify about product update
					return json.getString(TAG_KHACHHANG);

				} else {
					String mess = json.getString(TAG_MESSAGE);
					Toast.makeText(getApplicationContext(), mess.toString(), Toast.LENGTH_LONG);
				}
			} catch (JSONException e) {
				e.printStackTrace();
				Log.d("JSON out", json.toString());
			}

			return null;
		}


		/**
		 * After completing background task Dismiss the progress dialog
		 * *
		 */
		protected void onPostExecute(String str) {
			// dismiss the dialog once product uupdated
			if(str!="1")
			{
				Toast.makeText(getApplicationContext(), "Thong bao: " + str.toString(), Toast.LENGTH_LONG);
			}
			finish();
			pDialog.dismiss();
		}
	}
	class UpdateGPSKhachHangDetails extends AsyncTask<String, String, String> {
		/**
		 * Before starting background thread Show Progress Dialog
		 */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(Edit_khachHang.this);
			pDialog.setMessage("Saving GPS ...");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(true);
			pDialog.show();
		}

		/**
		 * Saving product
		 */
		protected String doInBackground(String... args) {

			// getting updated data from EditTexts
			GPSTracker gps;
			gps = new GPSTracker(getApplicationContext());
			if (gps.canGetLocation()) {

				double latitude = gps.getLatitude();
				double longitude = gps.getLongitude();

				try {
					objX.put(TAG_GPSLAT,Double.toString(latitude));
					objX.put(TAG_GPSLONG,Double.toString(longitude));
				} catch (JSONException e) {
					e.printStackTrace();
				}
			} else {
				// can't get location
				// GPS or Network is not enabled
				// Ask user to enable GPS/network in settings
				gps.showSettingsAlert();
			}
			// Building Parameters
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair(session.KEY_USERNAME, session.getUsername()));
			params.add(new BasicNameValuePair(session.KEY_PASSWORD, session.getPassword()));
			params.add(new BasicNameValuePair(session.TAG_DANGNHAP, "OK"));
			params.add(new BasicNameValuePair(session.TAG_THAOTAC, "UKH"));
			params.add(new BasicNameValuePair(session.TAG_PID,pid));
			params.add(new BasicNameValuePair(session.TAG_OBJ, objX.toString()));


			// sending modified data through http request
			// Notice that update product url accepts POST method
			JSONObject json = jsonParser.makeHttpRequest(session.URL,"POST", params);

			// check json success tag
			try {
				int success = json.getInt(TAG_SUCCESS);

				if (success == 1) {
					// send result code 100 to notify about product update
					return json.getString(TAG_KHACHHANG);

				} else {
					String mess = json.getString(TAG_MESSAGE);
					Toast.makeText(getApplicationContext(), mess.toString(), Toast.LENGTH_LONG);
				}
			} catch (JSONException e) {
				e.printStackTrace();
				Log.d("JSON out", json.toString());
			}

			return null;
		}


		/**
		 * After completing background task Dismiss the progress dialog
		 * *
		 */
		protected void onPostExecute(String str) {
			// dismiss the dialog once product uupdated
			if(str!="1")
			{
				Toast.makeText(getApplicationContext(), "Thong bao: " + str.toString(), Toast.LENGTH_LONG);
			}
			finish();
			pDialog.dismiss();
		}
	}
	/**
	 * **************************************************************
	 * Background Async Task to Delete Product
	 */
	class DeleteKhachHang extends AsyncTask<String, String, String> {

		/**
		 * Before starting background thread Show Progress Dialog
		 */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(Edit_khachHang.this);
			pDialog.setMessage("Deleting khach hang...");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(true);
			pDialog.show();
		}

		/**
		 * Deleting product
		 */
		protected String doInBackground(String... args) {
			// Building Parameters
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair(session.KEY_USERNAME, session.getUsername()));
			params.add(new BasicNameValuePair(session.KEY_PASSWORD, session.getPassword()));
			params.add(new BasicNameValuePair(session.TAG_DANGNHAP, "OK"));
			params.add(new BasicNameValuePair(session.TAG_THAOTAC, "DKH"));
			params.add(new BasicNameValuePair(session.TAG_PID, pid));
			params.add(new BasicNameValuePair(session.TAG_OBJ, objX.toString()));
			JSONObject json = jsonParser.makeHttpRequest(session.URL, "POST", params);
			// check your log for json response
			// json success tag

			try {
				int success = json.getInt(TAG_SUCCESS);

				if (success == 1) {
					// send result code 100 to notify about product update
					return json.getString(TAG_KHACHHANG);

				} else {
					String mess = json.getString(TAG_MESSAGE);
					Toast.makeText(getApplicationContext(), mess.toString(), Toast.LENGTH_LONG);
				}
			} catch (JSONException e) {
				e.printStackTrace();
				Log.d("JSON out", json.toString());
			}
			return null;
		}

		/**
		 * After completing background task Dismiss the progress dialog
		 * *
		 */
		protected void onPostExecute(String str) {
			if(str!="1")
			{
				Toast.makeText(getApplicationContext(), "Thong bao: " + str.toString(), Toast.LENGTH_LONG);
			}
			else
				finish();
			pDialog.dismiss();

		}

	}





	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.edit_khach_hang, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
}
